import React,{useState,useEffect} from "react"
import { useSingleState } from "nice-hooks";
import { withRouter,useHistory  } from 'react-router-dom'
import {
    Layout,
    Menu,
    Button,
    Popover,
    Input,
} from "antd"
import {
    MenuUnfoldOutlined,
    MenuFoldOutlined,
    UserOutlined,
    SearchOutlined
} from '@ant-design/icons'
import "./layouts.scss"
import className from "classnames"

import logo from "../asset/image/mao.png"
import headPortrait from "../asset/image/tou.jpeg"

import Routerlist from "./route"
import Item from "antd/lib/list/Item";

const { Header, Sider, Content } = Layout;
const { Search } = Input;
const { SubMenu } = Menu;

function Layouts(){
    // hooks写法，这样去获取的this.props
    let history=useHistory();
    // 菜单栏切换
    const [collapsed,collapsedToggle] = useState(false)
    const [openKeys, setOpenKeys] = useState([]);
    const [state, setState] = useSingleState({
        // 主题颜色
        theme:'light',//light;dark
        search:"",// 搜索value
        selectCurlt:history.location.pathname,//当前选中的菜单数组
        strmenu:0,
        strstr:[],
        openNum:[],
    });
    // 菜单板块
    const menu=[
        {
            mac:"/home",
            title:"首页",
            children:[]
        },
        {
            mac:"/list",
            title:"数据中心",
            children:[{
                mac:"/short",
                title:"ciYun分布",
                children:[]
            },{
                mac:"/muppet",
                title:"布偶",
                children:[
                    {
                        mac:"/zai",
                        title:"cat崽",
                        children:[{
                            mac:"/reanu",
                            title:"宠物",
                            children:[]
                        }]
                    },{
                        mac:"/catZasa",
                        title:"工作室",
                        children:[]
                    }
                ]
            },{
                mac:"/garfields",
                title:"earth分布",
                children:[
                    {
                        mac:"/shool",
                        title:"Hige",
                        children:[]
                    },
                    {
                        mac:"/garfield",
                        title:"kucas",
                        children:[]
                    }
                ]
            }]
        },
        {
            mac:"/news",
            title:"Cat趣事",
            children:[{
                mac:"/daily",
                title:"Daily Cat",
                children:[]
            },{
                mac:"/tiktok",
                title:"Tiktok Cat",
                children:[]
            }]
        }
    ];
    
    useEffect(()=>{
       digui(menu,0);
    },[])

    /*
        刷新页面，菜单栏继续保持展开状态
        1、逻辑：根据当前页面的history.location.pathname路径与菜单数组menu计算出每列展开的下标（递归digui()函数计算出），
        2、在通过下标递归gui()函数计算出每次展开的mac路径，
        3、最后setOpenKeys(state.openNum);自动展开菜单栏
    */
    const digui=(val,num)=>{
        val.forEach((item,index)=>{
            if(item.mac===history.location.pathname){
                if(num.toString().length>1){
                    let numstr=num.split("_");
                    numstr.splice(0,1)
                    setState({strstr:numstr},()=>{
                        gui(menu,state.strmenu,state.strstr,state.strstr.length)
                    })
                }
            }else{
                digui(item.children,num+'_'+index)
            }
        })
    }
    const gui=(array,number,array1,length)=>{
        if(number===length-1){
            state.openNum.unshift(array[array1[number]].mac)
            setState({openNum:state.openNum})
            setOpenKeys(state.openNum);
        }else{
            setState({strmenu:number+1})
            gui(array[array1[number]].children,state.strmenu,state.strstr,state.strstr.length)
            state.openNum.unshift(array[array1[number]].mac)
        }
    }

    // 默认跳转到首页
    if(history.location.pathname==="/"){
        history.push("/home");
        setState({
            selectCurlt:[history.location.pathname]
        })
    }

    // 菜单栏收缩展开
    const toggle = () =>{
        collapsedToggle(!collapsed);
    };
    // 个人中心
    const personal = ()=>{
        console.log("个人中心")
    }
    // 搜索value
    const onSearch = value => {
        setState({search:value},()=>{console.log(state.search)})
    };
    // 菜单点击跳转
    const menuClick = (e)=>{
        history.push(e.key);
    }
    // 菜单选中时调用
    const onSelect = (item, key, keyPath, selectedKeys, domEvent)=>{
        setState({
            selectCurlt:[item.key]
        })
    }

    const rootSubmenuKeys = [];
    menu.forEach((item,index)=>{
        if(item.children!==""){
            rootSubmenuKeys.push(item.mac)
        }
    })
    // 菜单栏手风琴效果收缩
    const onOpenChange = keys => {
        const latestOpenKey = keys.find(key => openKeys.indexOf(key) === -1);
        if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
          setOpenKeys(keys);
        } else {
          setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
        }
    };

    // 菜单无限分级封装
    const unite = (array)=>{
         return array.map((item=>{
            if(item.children.length===0){
                return <Menu.Item key={item.mac} icon={<UserOutlined />}>{item.title}</Menu.Item>
            }else{
                return <SubMenu title={item.title} key={item.mac} icon={<UserOutlined />}>
                    {unite(item.children)}
                </SubMenu>
            }
        }))
    }

    // 头像hover下面的dome内容
    const hoverContent = <ul className="loginUl">
        <li onClick={personal}>个人中心</li>
        <li>事项处理</li>
        <li>退出登录</li>
    </ul>;
    // 搜索框
    const searchComponent = <Search placeholder="请输入搜索内容" defaultValue={state.search} className={className('ind_scarch')} onSearch={onSearch} style={{ width: 200 }} />
    return(
        <Layout style={{minWidth:"1200px",margin:"0",padding:"0"}}>

            <Header className="site-layout-background" style={{ padding: 0,height:"70px", display:"flex",alignItems:"center",justifyContent:"space-between" }}>
                <div className="flexJu">
                    <div className="logo" style={{height:"64px",width:"200px",display:"flex",justifyContent:"center",backgroundColor:"#fff",alignItems:"center"}}>
                        <img style={{width:"200px",height:"100%",objectFit:"cover"}} src={logo} alt="logo" title="logo" />
                    </div>
                    <Button size="small" onClick={toggle} style={{ marginLeft: 16 }}>
                        {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined)}
                    </Button>
                </div>
                <div className="flexJu" style={{marginRight:"40px"}}>
                    <Popover
                        content={searchComponent}
                        trigger="hover"
                        placement="left"
                    >

                        <SearchOutlined style={{fontSize:18,color:"#999",marginRight:"18px",cursor:"pointer"}} />
                    </Popover>
                    
                    <Popover
                        style={{ width: "100px",border:"1px solid red" }}
                        content={hoverContent}
                        trigger="hover"
                    >
                        <div className="flexJu" style={{cursor:"pointer"}}>
                            <img
                                width={32}
                                height={32}
                                style={{borderRadius:"50%"}}
                                src={headPortrait}
                                alt="头像"
                                title="头像"
                            ></img>
                            <span className="potato_name">potato</span>
                        </div>
                    </Popover>
                </div>
            </Header>
            <Layout className="site-layout">
                <Sider
                    trigger={null} 
                    collapsible 
                    collapsed={collapsed}
                    style={{
                        overflow: 'auto',
                        height: 'calc(100vh - 70px)',
                    }}
                >
                    <Menu 
                        theme={state.theme} 
                        mode="inline" 
                        selectedKeys={state.selectCurlt}                        
                        style={{maxHeight:"100vh",height:'calc(100vh - 70px)'}}
                        onClick={menuClick}
                        onSelect={onSelect}
                        openKeys={openKeys}
                        onOpenChange={onOpenChange}
                    >
                        {unite(menu)}
                    </Menu>
                </Sider>

                <Content className="site-layout-background">
                    <Routerlist />
                </Content>
            </Layout>
        </Layout>
    )
}

export default withRouter(Layouts)